import requests
import random
import json
import hashlib
import base64
import time

AppId     = "xxxxxxxxx"        #APPID
AppSecret = "xxxxxxxxx"        #密钥
ApiUrl       = "https://iot-app-prod.fengdada.cn/mk/api" #API地址
PrinterId = "xxxxxxxxx"                         #打印机ID

#公共方法
def encode(BizData,nonce):
	jsonBytes = BizData.encode('utf-8')
	bizData = str(jsonBytes, 'utf-8')
	sign_ori = f"{bizData}{nonce}{AppSecret}"
	md5_hash = hashlib.md5(sign_ori.encode()).digest()
	sign = base64.b64encode(md5_hash).decode('utf-8')
	return sign

def generate_verification_code():
    verification_code = ""
    for i in range(6):
        verification_code += str(random.randint(0, 9))
    return verification_code

def DoMyPost(URL, json_BizData):
	ts = round(time.time() * 1000)
	nonce=generate_verification_code()
	sign=encode(json_BizData,nonce)
	data = {"bizData": json_BizData, "nonce": nonce,"appId": AppId,"timestamp": str(ts)}
	headers = {"Content-Type": "application/json","sign":sign}
	response = requests.post(URL, json=data, headers=headers)
	print(response.status_code)  # 输出响应状态码
	print(response.json())       # 输出响应结果（JSON 格式）

#云打印验证码
def PrintCaptcha(PrinterId):
	URL = ApiUrl+"/print/captcha"
	BizData = {'printerId': PrinterId}
	json_BizData = json.dumps(BizData)
	DoMyPost(URL, json_BizData)

#云打印机绑定
def PrintBind(PrinterId, VerificationCode):
	URL = ApiUrl+"/printer/bind"
	BizData = {'printerId': PrinterId,'captcha':VerificationCode}
	json_BizData = json.dumps(BizData)
	DoMyPost(URL, json_BizData)
#云打印
def Print(PrinterId, ShareCode, PrintDataList):
	URL = ApiUrl+"/print"
	BizData = {'printerId': PrinterId,'shareCode':ShareCode,'printData':PrintDataList}
	json_BizData = json.dumps(BizData)
	DoMyPost(URL, json_BizData)

#云打印状态查询
def QueryPrintStatus(PrinterId, ShareCode):
	URL = ApiUrl+"/printer/status/query"
	print(URL)
	BizData = {'printerId': PrinterId,'shareCode':ShareCode}
	json_BizData = json.dumps(BizData)
	DoMyPost(URL, json_BizData)

def main():
	#1、获取验证码
	#PrintCaptcha(PrinterId)
        
	#2、绑定打印机
	#VerificationCode = "xxxxxxxxx"
	#PrintBind(PrinterId, VerificationCode)

	#3、云打印
	ShareCode = "xxxxxxxxx"
	TemplateId = "xxxxxxxxx"
	waybillPrinterData ={
"receiveManAddress":"塘苗路18号",
"orderId":"10256485649",
"needFetch":"true",
"packageWeight":"",
"companyName":"",
"sendProvince":"浙江省",
"errorCode":"",
"receiverProvince":"浙江省",
"receiverCity":"杭州市",
"senderMan":"张三",
"senderArea":"西湖区",
"receiveMan":"李四",
"postStationId":"",
"itemName":"",
"specialType":"代收货款",
"senderPostcode":"",
"payMethod":"0",
"id":"1933",
"logisticCode":"BestSmart10256485649",
"machineCode":"1843923524226238",
"errorDesc":"",
"balanceStatus":"",
"specialMoney":" 39 元",
"expressType":"0",
"sendCounty":"西湖区",
"weight":"",
"receiverPostcode":"",
"version":"1",
"senderCity":"杭州市",
"receiveProvince":"浙江省",
"printResult":"NONE",
"sendMan":"张三",
"companyId":"",
"expressCost":"",
"receiverManPhone":"18598765432",
"mainId":"",
"senderManPhone":"15012345678",
"remark1":"",
"remark3":"",
"receiveCounty":"西湖区",
"remark2":"",
"lastUpdateTime":"Wed Jul 29 13:53:06 CST 2015",
"markDestination":"测-测试单(2)(浙-2)",
"sendCity":"杭州市",
"pkgCode":"测试测试包",
"receiverMan":"李四",
"errorInfo":"null",
"remark":"【批次1/1】备注",
"sendManPhone":"15012345678",
"batchId":"1/1",
"pickBy":"",
"result":"SUCCESS",
"mailNo":"12345678901234",
"shippingStatus":"NOMESSAGE",
"serialVersionUID":"-1229572053273904313",
"richItemInformation":"",
"receiveManPhone":"18598765432",
"udf7":"",
"billProvideSiteCode":"200000",
"logisticsProviderCode":"HTKY",
"udf8":"",
"printCount":"1",
"senderManAddress":"教工路1号",
"custId":"null",
"itemWeight":"",
"receiverManAddress":"塘苗路18号",
"isReprint":"false",
"orderSource":"BestSmart",
"udf5":"测试",
"udf6":"",
"senderProvince":"浙江省",
"receiverArea":"西湖区",
"udf3":"",
"udf4":"",
"udf1":"",
"userId":"",
"udf2":"",
"postStationName":"",
"itemCount":"0",
"logisticProviderID":"HTKY",
"billProvideSiteName":"上海分拨中心",
"createTime":"Wed Jul 29 13:37:40 CST 2015",
"receiveCity":"杭州市",
"sendManAddress":"教工路1号",
"printTime":"",
"username":""
}
	printDataList = [{"waybillPrinterData": waybillPrinterData, "templateId": TemplateId}] #使用append方法增加
	PData = printDataList
	#Print(PrinterId, ShareCode, PData)

	#4、云打印机状态查询
	#QueryPrintStatus(PrinterId, ShareCode)

if __name__ == '__main__':
    main()